from sc_engine.apps import messages as msgs
from sc_engine.youtube.service import get_starcraft_videos
from sc_engine.youtube.service import get_youtube_video
from sc_engine.youtube.service import get_author_videos, get_author_query_videos

def make_app(app_name, root_config, config):
    video_repo = get_youtube_video
    starcraft_repo = get_starcraft_videos
    author_repo = get_author_videos
    author_query_repo = get_author_query_videos

    app = YouTubeFetchApp(video_repo, starcraft_repo, author_repo, author_query_repo)

    return {
        msgs.YouTubeFetchRequested: app.youtube_fetch_requested,
        msgs.YouTubeVideoFetchRequested: app.youtube_video_fetch_requested,
        msgs.YouTubeAuthorFetchRequested: app.youtube_author_fetch_requested,
        msgs.YouTubeAuthorQueryFetchRequested: app.youtube_author_query_fetch_requested,
    }

class YouTubeFetchApp(object):
    """Fetch video data from youtube."""

    def __init__(self, video_repo, starcraft_repo, author_repo,
            author_query_repo):
        self.video_repo = video_repo
        self.starcraft_repo = starcraft_repo
        self.author_repo = author_repo
        self.author_query_repo = author_query_repo

    def youtube_fetch_requested(self, msg):
        results = self.starcraft_repo(msg.start_date, msg.end_date)

        return [msgs.YouTubeFetchAnnouncement(**x) for x in results]

    def youtube_video_fetch_requested(self, msg):
        result = self.video_repo(msg.video_id)

        return msgs.YouTubeFetchAnnouncement(**result)

    def youtube_author_fetch_requested(self, msg):
        results = self.author_repo(msg.author, msg.start_date, msg.end_date)

        return [msgs.YouTubeFetchAnnouncement(**x) for x in results]

    def youtube_author_query_fetch_requested(self, msg):
        results = self.author_query_repo(msg.author, msg.query)

        return [msgs.YouTubeFetchAnnouncement(**x) for x in results]

